//
//  LoginProtocolAlertView.swift
//  Scanread
//
//  Created by Macintosh on 2023/7/15.
//

import UIKit

class LoginProtocolAlertView: UIView {

    var clickBlock: ((_ index: Int) -> Void)?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        createSubViews()
    }

    @available(*, unavailable)
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    func createSubViews() {
        backgroundColor = UIColor.clear
        frame = UIScreen.main.bounds
        
        addSubview(alphaView)
        alphaView.snp.makeConstraints { make in
            make.left.right.top.bottom.equalToSuperview()
        }
        
        addSubview(contentView)
        contentView.snp.makeConstraints { make in
            make.center.equalToSuperview()
            make.width.equalTo(290)
            make.height.equalTo(170)
        }
        
        contentView.addSubview(titleLabel)
        titleLabel.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.top.equalTo(20)
        }
        
        contentView.addSubview(textView)
        textView.snp.makeConstraints { make in
            make.top.equalTo(titleLabel.snp.bottom).offset(10)
            make.left.equalTo(10)
            make.right.equalTo(-10)
            make.height.equalTo(50)
        }
        
        contentView.addSubview(leftBtn)
        leftBtn.snp.makeConstraints { make in
            make.left.equalTo(25)
            make.bottom.equalTo(-20)
            make.height.equalTo(32)
            make.width.equalTo(110)
        }

        contentView.addSubview(rightBtn)
        rightBtn.snp.makeConstraints { make in
            make.right.equalTo(-25)
            make.bottom.equalTo(-20)
            make.height.equalTo(32)
            make.width.equalTo(110)
        }

    }
    
    static func show(_ cancel: String? = "取消", done: String = "同意", click: ((_ index: Int) -> Void)? = nil) {
        let view = LoginProtocolAlertView()
        view.clickBlock = click
        view.show()
    }

    func show(inView: UIView? = nil) {
        if inView != nil {
            inView!.addSubview(self)
        } else {
            UIApplication.shared.delegate?.window??.addSubview(self)
        }
        
        alpha = 0
        UIView.animate(withDuration: 0.1, animations: { () -> Void in
            self.alpha = 1.0
        })

        let previousTransform = contentView.transform
        contentView.layer.transform = CATransform3DMakeScale(0.9, 0.9, 0.0)
        UIView.animate(withDuration: 0.2, animations: { () -> Void in
            self.contentView.layer.transform = CATransform3DMakeScale(1.1, 1.1, 0.0)
        }, completion: { (_) -> Void in
            UIView.animate(withDuration: 0.1, animations: { () -> Void in
                self.contentView.layer.transform = CATransform3DMakeScale(0.9, 0.9, 0.0)
            }, completion: { (_) -> Void in
                UIView.animate(withDuration: 0.1, animations: { () -> Void in
                    self.contentView.layer.transform = CATransform3DMakeScale(1.0, 1.0, 0.0)
                }, completion: { (_) -> Void in
                    self.contentView.transform = previousTransform
                })
            })
        })
    }
    lazy var alphaView: UIView = {
        let alphaView = UIView()
        alphaView.backgroundColor = UIColor.black
        alphaView.alpha = 0.34

        return alphaView
    }()

    lazy var contentView: UIView = {
        let contentView = UIView()
        contentView.backgroundColor = UIColor.white
        contentView.layer.masksToBounds = true
        contentView.layer.cornerRadius = 8

        return contentView
    }()
    
    lazy var titleLabel: UILabel = {
        let titleLabel = UILabel()
        titleLabel.textAlignment = .center
        titleLabel.font = UIFont.systemFont(ofSize: 14)
        titleLabel.text = "提示"
        titleLabel.textColor = UIColor.black

        return titleLabel
    }()

    lazy var textView: UITextView = {
        let tv = UITextView()
        tv.isEditable = false
        tv.delegate = self
        tv.dataDetectorTypes = []

        let text = "为保证你的权益，请阅读并同意《隐私协议》和《用户协议》"
        let attrs = NSMutableAttributedString(string: text, attributes: [.foregroundColor: UIColor.black, .font: UIFont.systemFont(ofSize: 16)])
        let linkValue = "app://privacy"
        let range = (text as NSString).range(of: "《隐私协议》")
        attrs.addAttribute(.link, value: linkValue, range: range)
        let userLink = "app://user"
        let userRange = (text as NSString).range(of: "《用户协议》")
        attrs.addAttribute(.link, value: userLink, range: userRange)
        tv.attributedText = attrs
        tv.linkTextAttributes = [.foregroundColor: UIColor(valueRGB: UInt(OEMInfo.themeHex), alpha: 1.0)]

        return tv
    }()
    
    lazy var leftBtn: UIButton = {
        let leftBtn = UIButton()
        leftBtn.layer.cornerRadius = 10
        leftBtn.setTitle("取消", for: .normal)
        leftBtn.setTitleColor(UIColor.black, for: .normal)
        leftBtn.titleLabel?.font = UIFont.systemFont(ofSize: 14)
        leftBtn.backgroundColor = UIColor(valueRGB: 0xF4F4FA, alpha: 1.0)
        leftBtn.addTarget(self, action: #selector(actionLeft), for: .touchUpInside)

        return leftBtn
    }()

    lazy var rightBtn: UIButton = {
        let rightBtn = UIButton()
        rightBtn.backgroundColor = UIColor(valueRGB: UInt(OEMInfo.themeHex), alpha: 1.0)
        rightBtn.layer.cornerRadius = 10
        rightBtn.setTitle("确认", for: .normal)
        rightBtn.titleLabel?.font = UIFont.systemFont(ofSize: 14)
        rightBtn.addTarget(self, action: #selector(actionRight), for: .touchUpInside)

        return rightBtn
    }()

    @objc
    func actionLeft() {
        if let clickBlock = clickBlock {
            clickBlock(0)
            removeFromSuperview()
        }
    }

    @objc
    func actionRight() {
        if let clickBlock = clickBlock {
            clickBlock(1)
            removeFromSuperview()
        }
    }

}

extension LoginProtocolAlertView: UITextViewDelegate {
    func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool {
        if URL.absoluteString.contains("privacy") == true {
            let web = WebViewController()
            web.modalPresentationStyle = .fullScreen
            web.url = UserDefaults.standard.value(forKey: UserDefaultsKey.sercurityProtocol) as? String ?? ""
            topViewController?.present(web, animated: true)
            return false
        }else if URL.absoluteString.contains("user") == true {
            let web = WebViewController()
            web.modalPresentationStyle = .fullScreen
            web.url = UserDefaults.standard.value(forKey: UserDefaultsKey.userProtocol) as? String ?? ""
            topViewController?.present(web, animated: true)
            return false
        }
        return true
    }
}
